<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use App\Http\Requests\MechanismAuth;
use App\Models\Mechanism;
use App\Models\Region;
use Illuminate\Http\Request;


class MechanismController extends Controller
{
    // 机构列表
    public function index()
    {
        $result = Mechanism::paginate($this->limit, [
            'id', 'desc', 'name',
            's_num', 'province_id', 'city_id',
            'area_id', 'address', 'mobile',
            'cert_img', 'cover', 'province_name',
            'city_name', 'area_name'
        ]);
        return $this->writeJson(0, $result->items());
    }

    // 认证-数据新增/编辑
    public function auth(MechanismAuth $request)
    {
        $model = Mechanism::whereUserId(auth('wechat')->id())
            ->first();
        if (empty($model)) {
            $model = new Mechanism();
            $model->user_id = auth('wechat')->id();
        }
        $model->status = 0;
//        $model->setRawAttributes($request->validated());
        $model->desc = $request->post('desc');
        $model->name = $request->post('name');
        $model->s_num = $request->post('s_num');
        $model->province_id = $request->post('province_id');
        $model->city_id = $request->post('city_id');
        $model->area_id = $request->post('area_id');
        $model->address = $request->post('address');
        $model->mobile = $request->post('mobile');
        $model->cert_img = $request->post('cert_img');
        $model->cover = $request->post('cover');
        $model->province_name = Region::whereId($model->province_id)->value('name');
        $model->city_name = Region::whereId($model->city_id)->value('name');
        $model->area_name = Region::whereId($model->area_id)->value('name');
        $model->save();

        return $this->writeJson(0, null, '提交成功');
    }

    // 获取认证信息
    public function getDataAuth(Request $request)
    {
        $id = $request->post('id');
        $data = Mechanism::find($id, [
            'id', 'desc', 'name',
            's_num', 'province_id', 'city_id',
            'area_id', 'address', 'mobile',
            'cert_img', 'cover', 'province_name',
            'city_name', 'area_name'
        ]);
        return $this->writeJson(0, $data);
    }
}
